<script setup lang="tsx">
import { RadioGroup, Select, SelectOption } from 'ant-design-vue'
import { computed, onMounted, ref, watch } from 'vue'
import { dicts, getDict } from '../../hooks/useDict'
const props = defineProps({
  options: {
    type: Array,
    default: () => []
  },
  api: Function,
  type: String,
  dict: String,
  transformOption: {
    type: Function,
    default: (item: any) => item
  },
  placeholder: {
    type: String,
    default: '请输入'
  },
  display: {
    type: Boolean,
    default: undefined
  },
  fieldNames: {
    type: Object,
    default: null
  }
})

const apiOptions = ref([])

const value = defineModel<any>('value')
onMounted(async () => {
  if (props.dict) {
    getDict(props.dict)
  }
  if (props.api) {
    const data = await props.api()
    const fieldNames = props.fieldNames || {}
    apiOptions.value = data.map((item: any) => {
      return {
        label: item[fieldNames.label || 'label'],
        value: item[fieldNames.value || 'value']
      }
    })
  }
})
const emit = defineEmits(['changeObj'])
const myOptions = computed(() => {
  if (props.dict) {
    return props.transformOption(dicts[props.dict] || [])
  }

  return props.transformOption(props.api ? apiOptions.value : props.options)
})
watch(value, () => {
  let item = myOptions.value.find((t: any) => t.value == value.value)
  if (item) {
    emit('changeObj', item)
  }
})
</script>
<template>
  <div v-if="display">{{ myOptions.find((t:any) => t.value == value)?.label }}</div>
  <RadioGroup
    v-bind="$attrs"
    v-model:value="value"
    v-else-if="type === 'radio'"
    :options="myOptions"
  ></RadioGroup>
  <Select allow-clear v-bind="$attrs" v-model:value="value" v-else :placeholder="placeholder">
    <SelectOption
      v-for="item in myOptions"
      :key="item.value"
      :value="item.value"
      :label="item.label"
      :disabled="item.disabled"
      >{{ item.label }}</SelectOption
    >
  </Select>
</template>
<style module lang="scss"></style>
